package cn.powertime.evaluation.facade.impl;

import cn.powertime.evaluation.annotation.Facade;
import cn.powertime.evaluation.entity.DbqNews;
import cn.powertime.evaluation.exception.BusinessException;
import cn.powertime.evaluation.facade.DbqNewsFacade;
import cn.powertime.evaluation.service.DbqNewsService;
import cn.powertime.evaluation.vo.ParamPageVo;
import cn.powertime.evaluation.vo.WebReqNewsSearchVo;
import cn.powertime.evaluation.vo.WebRespNewsListVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Facade
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class DbqNewsFacadeImpl implements DbqNewsFacade {

    @Autowired
    private DbqNewsService dbqNewsService;

    @Override
    public IPage<WebRespNewsListVo> newsList(ParamPageVo<WebReqNewsSearchVo> vo) {

        Page<DbqNews> page = new Page<>(vo.getPage().getCurrent(), vo.getPage().getSize());
        IPage<WebRespNewsListVo> indexList = dbqNewsService.newsList(page,vo.getParams());
        //查询新闻获取文章内容中的图片最为首页的代表图片
        if(vo.getParams().getType() == 1){
            indexList.getRecords().forEach(item-> {
                Document document = Jsoup.parse(item.getContent());  //  将字符串解析成Document对象
                Elements elements = document.select("img");
                if(elements.size() > 0){
                    String element = elements.get(0).toString();
                    item.setImg(element);
                }
            });
        }
        return indexList;
    }

    @Override
    public WebRespNewsListVo details(Long newsId) {
        DbqNews news = dbqNewsService.getById(newsId);
        long pv = news.getNewsWarePv();
        pv++;
        DbqNews dbqNews = new DbqNews();
        dbqNews.setNewsWarePv(pv);
        dbqNews.setId(newsId);
        boolean b = dbqNewsService.updateById(dbqNews);
        if(!b){
            throw new BusinessException("增加浏览量失败");
        }
        WebRespNewsListVo vo = new WebRespNewsListVo();
        BeanUtils.copyProperties(news,vo);
        vo.setCreateDate(news.getCreateTime());
        return vo;
    }

}
